﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Derrick.Web
{
    public partial class TestTwitterRest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //GS - Get the oAuth params
            string status = "your status";
            string postBody = "status=" +
                Uri.EscapeDataString(status);

            string oauth_consumer_key = "MeRJZn4Tx3S7BTEf5ToSw";
            string oauth_nonce = Convert.ToBase64String(
                new ASCIIEncoding().GetBytes(
                    DateTime.Now.Ticks.ToString()));

            string oauth_signature_method = "HMAC-SHA1";
            string oauth_token =
                "1264407572-7kDxIvgULA3tS0gPga1t9uXXeJOP6hD0c98VFjG";

            TimeSpan ts = DateTime.UtcNow -
                new DateTime(1970, 1, 1, 0, 0, 0, 0);

            string oauth_timestamp =
                Convert.ToInt64(ts.TotalSeconds).ToString();

            string oauth_version = "1.0";

            //GS - When building the signature string the params
            //must be in alphabetical order. I can't be bothered
            //with that, get SortedDictionary to do it's thing
            SortedDictionary<string, string> sd =
                new SortedDictionary<string, string>();

            sd.Add("status", status);
            sd.Add("oauth_version", oauth_version);
            sd.Add("oauth_consumer_key", oauth_consumer_key);
            sd.Add("oauth_nonce", oauth_nonce);
            sd.Add("oauth_signature_method", oauth_signature_method);
            sd.Add("oauth_timestamp", oauth_timestamp);
            sd.Add("oauth_token", oauth_token);

            //GS - Build the signature string
            string baseString = String.Empty;
            baseString += "POST" + "&";
            //https://api.twitter.com/1/statuses/user_timeline.json?screen_name=metrolinx
            baseString += Uri.EscapeDataString(
                //"http://api.twitter.com/1/statuses/update.json")
                "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=metrolinx")
                + "&";

            foreach (KeyValuePair<string, string> entry in sd)
            {
                baseString += Uri.EscapeDataString(entry.Key +
                    "=" + entry.Value + "&");
            }

            //GS - Remove the trailing ambersand char, remember 
            //it's been urlEncoded so you have to remove the 
            //last 3 chars - %26
            baseString =
                baseString.Substring(0, baseString.Length - 3);

            //GS - Build the signing key
            string consumerSecret =
                "jNaFedHHbSkuWOW1e1cVUgK4V9VblB13fZttfGlH30";

            string oauth_token_secret =
                "80GMSUebVQOtyVQkVwYxqTh2I6lvwGmlRiERwJt8d1I";

            string signingKey =
                Uri.EscapeDataString(consumerSecret) + "&" +
                Uri.EscapeDataString(oauth_token_secret);

            //GS - Sign the request
            HMACSHA1 hasher = new HMACSHA1(
                new ASCIIEncoding().GetBytes(signingKey));

            string signatureString = Convert.ToBase64String(
                hasher.ComputeHash(
                new ASCIIEncoding().GetBytes(baseString)));

            //GS - Tell Twitter we don't do the 100 continue thing
            ServicePointManager.Expect100Continue = false;

            //GS - Instantiate a web request and populate the 
            //authorization header
            HttpWebRequest hwr =
                (HttpWebRequest)WebRequest.Create(
                @"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=metrolinx");

            string authorizationHeaderParams = String.Empty;
            authorizationHeaderParams += "OAuth ";
            authorizationHeaderParams += "oauth_nonce=" + "\"" +
                Uri.EscapeDataString(oauth_nonce) + "\",";

            authorizationHeaderParams +=
                "oauth_signature_method=" + "\"" +
                Uri.EscapeDataString(oauth_signature_method) +
                "\",";

            authorizationHeaderParams += "oauth_timestamp=" + "\"" +
                Uri.EscapeDataString(oauth_timestamp) + "\",";

            authorizationHeaderParams += "oauth_consumer_key="
                + "\"" + Uri.EscapeDataString(
                oauth_consumer_key) + "\",";

            authorizationHeaderParams += "oauth_token=" + "\"" +
                Uri.EscapeDataString(oauth_token) + "\",";

            authorizationHeaderParams += "oauth_signature=" + "\""
                + Uri.EscapeDataString(signatureString) + "\",";

            authorizationHeaderParams += "oauth_version=" + "\"" +
                Uri.EscapeDataString(oauth_version) + "\"";

            hwr.Headers.Add(
                "Authorization", authorizationHeaderParams);

            //GS - POST off the request
            hwr.Method = "GET";
            hwr.ContentType = "application/x-www-form-urlencoded";
            //Stream stream = hwr.GetRequestStream();
            //byte[] bodyBytes =
            //    new ASCIIEncoding().GetBytes(postBody);

            //stream.Write(bodyBytes, 0, bodyBytes.Length);
            //stream.Flush();
            //stream.Close();

            //GS - Allow us a reasonable timeout in case
            //Twitter's busy
            hwr.Timeout = 3 * 60 * 1000;

            try
            {
                HttpWebResponse rsp = hwr.GetResponse()
                    as HttpWebResponse;
                //GS - Do something with the return here...
                Stream responseStream = rsp.GetResponseStream();
                byte[] messageBytes = new byte[1024];

                while (responseStream.Read(messageBytes, 0, messageBytes.Length) > 0)
                {
                    string message = Encoding.UTF8.GetString(messageBytes);
                    Response.Write(message);
                }
                
            }
            catch (WebException ex)
            {
                //GS - Do some clever error handling here...
                Response.Write(ex.ToString());
            }
        }

    }
}